package cn.ccenjie.wsy.config.vcode;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class VcodeProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        Assert.notNull(authentication.getPrincipal(), "vcode is empty");
        String vcode = authentication.getPrincipal().toString();
        String serverVcode = serverVcode();
        if(!vcode.equals(serverVcode)) {
            throw new BadCredentialsException("验证码不正确");
        }

        return authentication;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.isAssignableFrom(VcodeToken.class);
    }

    private String serverVcode() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(attrs, "attrs is empty");
        Object vcode = attrs.getRequest().getSession().getAttribute("captcha");
        return vcode == null ? null : vcode.toString();

    }
}
